import { loginAPI, registerAPI } from "@/api/user";
import router from "@/router";
import { Message } from "element-ui";
import { delToken, getToken, setToken } from "@/utils/storage";

export default {
  namespaced: true,
  state: {
    token: getToken(),
  },
  getters: {},
  mutations: {
    setTokenJs(state, token) {
      state.token = token;
      setToken(token);
    },
    showInfo(state, text) {
      Message.success(`${text}`);
    },
    layOutJs(state) {
      state.token = "";
      delToken();
    },
  },
  actions: {
    // 注册
    async registerJs(context, data) {
      const res = await registerAPI(data);
      //   console.log(res);
      context.commit("showInfo", "注册成功");
      setTimeout(() => {
        router.push("/login");
      }, 1500);
    },
    // 登录
    async loginJS(context, data) {
      const res = await loginAPI(data);
      setTimeout(() => {
        router.push("/students");
      }, 1500);
      context.commit("setTokenJs", res.data.data.token);
      context.commit("showInfo", "登录成功");
    },
  },
};
